﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace wage.Forms
{
    public partial class workTimeEntry : baseClass.Forms.baseStatementOnly
    {
        public workTimeEntry()
        {
            InitializeComponent();
            try
            {
                this.SetDataType(CommonTypes.Settings.sysStatementTypes.GetCode(CommonTypes.VoucherType.StatementWageWorkTimeCount));
                this.myDetailGrid.SetDataSource(myWageDS.wgWorkTime);
            }
            catch (Exception ex)
            {
                this.ErrorHandler(this, ex);
            }
        }

        #region virtual
        #endregion 
        
        short? _WorkShipDurationInMin = null;
        short WorkShipDurationInMin
        {
            get
            {
                if (_WorkShipDurationInMin == null)
                {
                    data.wageDS.wgWorkShiftRow workShiftRow = DataAccess.DataCache.FindWorkShip(workShiftCodeEd.Text);
                    _WorkShipDurationInMin = (short)(workShiftRow == null ? 0 : workShiftRow.durationInMin);
                }
                return _WorkShipDurationInMin.Value;
            }
        }

        private static void UpdateWorkTime(data.wageDS.wgWorkTimeRow row, short WorkShipDurationInMin)
        {
            row.workMins = (short)(WorkShipDurationInMin - row.comeLateMins - row.leaveEarlyMins);
        }

        #region override
       
        protected override bool CancelAllChanges()
        {
            base.CancelAllChanges();
            this.myDetailGrid.myEditDataSource.CancelEdit();
            myWageDS.wgWorkTime.RejectChanges();
            this.ShowMessage("");
            return true;
        }
        protected override DataRow FindMasterRecord(string editKeyType, string editKey, bool showList)
        {
            baseClass.Libs.myStatementFind.SetStatementType(editKeyType);
            baseClass.Libs.myStatementFind.Find(editKey, showList);
            return (DataRow)baseClass.Libs.myStatementFind.mySelectedDataRow;
        }
        protected override bool DataValid(bool showMsg)
        {
            ClearNotifyError();
            bool retVal = base.DataValid(showMsg);
            if (workShiftCodeEd.Visible && workShiftCodeEd.Text.Trim() == "")
            {
                NotifyError(workShiftCodeLbl);
                retVal = false;
            }
            return retVal;
        }

        protected override bool FillMasterTable(string editKeyId)
        {
            if (base.FillMasterTable(editKeyId) == false) return false;
            workShiftCodeEd_Validated(null, null);
            return true;
        }
        protected override bool FillDetailTable(string editKeyId)
        {
            myWageDS.wgWorkTime.Clear();
            DataAccess.DataLibs.LoadData(myWageDS.wgWorkTime, editKeyId);
            foreach (data.wageDS.wgWorkTimeRow row in myWageDS.wgWorkTime)
            {
                DataAccess.DataCache.FindEmployee(row.emCode);
            }
            return true;
        }
        public override void LockEdit()
        {
            base.LockEdit();
            bool lockState = this.isLockEdit;
            this.workShiftCodeEd.Enabled = !lockState;
            this.updateDataBtn.Enabled = !lockState;
        }

        protected override void ArrangeForm()
        {
            base.ArrangeForm();
            this.myWorkTimeGrid.AutoFit();
        }

        protected override bool BeforeSaveMasterRecord(DataRowView dataRow)
        {
            if (base.BeforeSaveMasterRecord(dataRow) == false) return false;
            return true;
        }
        protected override bool SaveDetailData(string statementId)
        {
            this.myDetailGrid.myEditDataSource.EndEdit();
            DataAccess.DataLibs.UpdateData(myWageDS.wgWorkTime);
            return base.SaveDetailData(statementId);
        }
        protected override common.controls.baseDataGridView CreateDetailGrid()
        {
            Controls.gridWorkTime grid = new Controls.gridWorkTime();
            grid.Init();
            grid.CellValueChanged += new DataGridViewCellEventHandler(workTime_OnDetailCellValueChanged);
            return grid;
        }
        protected override void OnValidateDetailRow(DataGridViewRow row, common.controls.GridRowValidateEventArgs e)
        {
            if (row.DataBoundItem == null || e.HaveError) return;
            data.wageDS.wgWorkTimeRow detailRow = (data.wageDS.wgWorkTimeRow)((DataRowView)row.DataBoundItem).Row;
            detailRow.statementId = statementIdEd.Text;
            if (application.CheckData.Check(detailRow,e.ErrorText) == false) e.HaveError = true;
        }

        protected override bool IsNeedUpdateGridTotal(common.controls.GridEventArgs e)
        {
            return this.myDetailGrid.IsValidCell(e.RowIndex, e.ColumnIndex) &&
                  (this.myDetailGrid.Columns[e.ColumnIndex].Name == wage.Controls.gridWorkTime.ColumnNames.WorkMins.ToString());
        }
        #endregion override

        #region event handler
        private void workTime_OnDetailCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (this.myDetailGrid.CurrentCell == null || !this.myDetailGrid.IsValidCell(e.RowIndex, e.ColumnIndex)) return;
            try
            {
                if (this.myDetailGrid.IsOnProcessing) return;
                this.myDetailGrid.IsOnProcessing = true;

                if (this.myDetailGrid.CurrentRow.DataBoundItem == null) return;
                data.wageDS.wgWorkTimeRow workTimeRow = (data.wageDS.wgWorkTimeRow)(((DataRowView)this.myDetailGrid.CurrentRow.DataBoundItem)).Row; 
                //Duration
                if (this.myDetailGrid.Columns[e.ColumnIndex].Name == wage.Controls.gridWorkTime.ColumnNames.EmCode.ToString() ||
                    this.myDetailGrid.Columns[e.ColumnIndex].Name == wage.Controls.gridWorkTime.ColumnNames.ComeLateInMins.ToString()||
                    this.myDetailGrid.Columns[e.ColumnIndex].Name == wage.Controls.gridWorkTime.ColumnNames.LeaveEarlyInMins.ToString())
                {
                    UpdateWorkTime(workTimeRow, this.WorkShipDurationInMin); 
                    //this.myDetailGrid.myEditDataSource.ResetBindings(false);
                }
                this.myDetailGrid.IsOnProcessing = false;
            }
            catch (Exception er)
            {
                this.myDetailGrid.IsOnProcessing = false;
                this.ErrorHandler(this, er);
            }
        }
        private void updateDataBtn_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show(String.Format("Cập nhật lại giờ công theo thông số ca : {0} ?",this.workShiftCodeEd.Text), common.Settings.sysApplicationName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) 
                return ;
            try
            {
                this._WorkShipDurationInMin = null;
                foreach (DataGridViewRow  row in this.myDetailGrid.Rows)
                {
                    if (row.DataBoundItem == null) continue;
                    data.wageDS.wgWorkTimeRow workTimeRow = (data.wageDS.wgWorkTimeRow)(((DataRowView)row.DataBoundItem)).Row; 
                    UpdateWorkTime(workTimeRow,this.WorkShipDurationInMin); 
                }
                this.myDetailGrid.myEditDataSource.ResetBindings(false);
            }
            catch (Exception er)
            {
                this.ErrorHandler(this, er);
            }
        }

        private void workShiftCodeEd_Validated(object sender, EventArgs e)
        {
            try
            {
                data.wageDS.wgWorkShiftRow workShiftRow = DataAccess.DataCache.FindWorkShip(workShiftCodeEd.Text);
                if (workShiftRow==null) 
                {
                    workShiftInfoLbl.Text ="";
                    return;
                }
                workShiftInfoLbl.Text = workShiftRow.name + " " + common.timeLibs.Min2Str(workShiftRow.durationInMin);
            }
            catch (Exception er)
            {
                this.ErrorHandler(this, er);
            }

        }
        #endregion event handler
    }

}
